<?php
namespace app\common\traits;
use app\post\model\Tag;
use think\Cache;

/**
 * 控制器基础服用
 * Class ControllerCurd
 * @package app\common\traits
 */
trait ControllerCurd
{
    /**
     * Notes:添加操作
     * User: chenping
     * email: 375129701@qq.com
     * @return mixed
     */
    protected function add($jump='' , $closure='',$data=[])
    {
        if($this->request->isAjax() || $this->request->isPost())
        {
            if($data){
                $input = $data;
            }else{
                $input = $this->request->post();
            }
            $result= $this->model->createDatas($input);
            if($result)
            {
                //\think\facade\Cache::clear();
                if($closure)
                {
                    $closure($this->model,$result);
                }
                $this->success("保存成功", $jump,$result);
            }else{
                $this->error('保存失败',$jump,$input);
            }

        }

    }

    /**
     * Notes:编辑操作
     * User: chenping
     * email: 375129701@qq.com
     * @return mixed
     */
    protected function edit($jump='', $closure='',$data=[])
    {
        if($this->request->isAjax() || $this->request->isPost())
        {
            if($data){
                $input = $data;
            }else{
                $input = $this->request->post();
            }

            $result= $this->model->updateDatas($input);

            if($result)
            {
                //\think\facade\Cache::clear();
                if($closure)
                {
                    $closure($this->model,$input);
                }
                $this->success("保存成功", $jump,$input);
            }else{
                $this->error('保存失败',$jump,$input);
            }
        }
    }

    /**
     * Notes:删除操作
     * User: chenping
     * email: 375129701@qq.com
     * @return mixed
     */
    protected function del($jump='',$closure='',$data=[])
    {
        if($this->request->isAjax() || $this->request->isPost())
        {
            if($data){
                $input = $data;
            }else{
                $input = $this->request->param("idList",0,"intval");
            }

            if(is_string($input)) $input = explode(",",$input);

            if(empty($input)) $this->error("请选择所需要删除的数据！");

            $data = $this->model->where("id","in",$input)->select()->toArray();

            $result= $this->model->deleteDatas($input);

            if($result)
            {
                //\think\facade\Cache::clear();
                if($closure)
                {
                    $closure($this->model,$input,$data);
                }
                $this->success("删除成功", $jump);
            }else{
                $this->error('删除失败',$jump);
            }
        }else{
            $this->error("请求错误");
        }
    }


}